// Copyright (c) 2014 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.

package com.wlit;

import com.formdev.flatlaf.FlatLightLaf;
//import com.xhb.tianping.IDataListener;
import com.wlit.ui.Tab;
import com.wlit.ui.TabButton;
import com.wlit.ui.TabFactory;
import com.wlit.ui.TabbedPane;
import com.wlit.ui.resources.Resources;
//import com.xhb.websocket.WebSocketServer;
import me.friwi.jcefmaven.CefAppBuilder;
import me.friwi.jcefmaven.CefInitializationException;
import me.friwi.jcefmaven.MavenCefAppHandlerAdapter;
import me.friwi.jcefmaven.UnsupportedPlatformException;
import org.cef.CefApp;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.util.Arrays;

/**
 * 应用启动类
 */
public class JavaBrowserApplication extends JFrame {
    private static final long serialVersionUID = -5570653778104813836L;

    private final CefApp cefApp;

    public static JFrame mainFrame;

    public static TabbedPane tabbedPane;

    //public static List<IDataListener> dataListeners = new ArrayList<>();


    private JavaBrowserApplication(String[] args) throws UnsupportedPlatformException, CefInitializationException, IOException, InterruptedException {
        FlatLightLaf.setup();
        CefAppBuilder builder = new CefAppBuilder();
        //设置华为镜像，加载比较快
        builder.setMirrors(Arrays.asList("http://mirrors.huaweicloud.com/repository/maven/me/friwi/jcef-natives-{platform}/{tag}/jcef-natives-{platform}-{tag}.jar"));
        // 关闭离屏模式
        builder.getCefSettings().windowless_rendering_enabled = false;

        builder.setAppHandler(new MavenCefAppHandlerAdapter() {
            @Override
            public void stateHasChanged(org.cef.CefApp.CefAppState state) {
                // 窗口关闭的时候 退出
                if (state == CefApp.CefAppState.TERMINATED) System.exit(0);
            }
        });

        if (args.length > 0) {
            builder.addJcefArgs(args);
        }
        cefApp = builder.build();
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                initAndDisplayUI();
            }
        });
        mainFrame = this;
        //启动websocket服务
//        WebSocketServer webSocketServer = new WebSocketServer();
//        webSocketServer.start();
    }

    public static void main(String[] args) throws UnsupportedPlatformException, CefInitializationException, IOException, InterruptedException {
        new JavaBrowserApplication(args);
    }

    private void initAndDisplayUI() {
        tabbedPane = new TabbedPane();
        Tab tab = TabFactory.createTab("http://baidu.com", cefApp);
        insertTab(tab);
        insertNewTabButton();
        this.setTitle("Java浏览器");
        this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        this.addWindowListener(new WindowAdapter() {
            @SuppressWarnings("CallToSystemExit")
            @Override
            public void windowClosing(WindowEvent e) {
                tabbedPane.disposeAllTabs();
                System.exit(0);
            }
        });
        this.add(tabbedPane, BorderLayout.CENTER);
        //实现默认全屏
//        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
//        ge.getDefaultScreenDevice().setFullScreenWindow(this);

        //this.setUndecorated(true);
        this.pack();
        this.setSize(1024, 700);
        this.setLocationRelativeTo(null);
        this.setIconImage(Resources.getIcon("browser16x16.png").getImage());

        this.setExtendedState(JFrame.MAXIMIZED_BOTH); //最大化
        //this.setAlwaysOnTop(true); //总在最前面

        this.setVisible(true);
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                CefApp.getInstance().dispose();
                dispose();
            }
        });
    }

    private void insertNewTabButton() {
        TabButton button = new TabButton(Resources.getIcon("new-tab.png"), "New tab");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(final ActionEvent e) {
                insertTab( TabFactory.createTab(cefApp));
            }
        });
        tabbedPane.addTabButton(button);
    }

    public static void insertTab(Tab tab) {
        tabbedPane.addTab(tab);
        tabbedPane.selectTab(tab);
    }
}
